<template>
	<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
		<div style="margin-bottom: 20px">
			<el-radio-group v-model="loginForm.type" size="large">
				<el-radio-button :label="0">密码登录</el-radio-button>
				<el-radio-button :label="1">短信登录</el-radio-button>
			</el-radio-group>
		</div>

		<div class="phoneForm">
			<el-form-item prop="area_code" style="flex: 2; margin-right: 5px; margin-bottom: 20px">
				<el-select v-model="loginForm.area_code" class="m-2" placeholder="区号" size="large">
					<el-option
						v-for="item in codeList"
						:key="item.area_code"
						:label="'+' + item.area_code + ' ' + item.area_name"
						:value="item.area_code"
					/>
				</el-select>
			</el-form-item>
			<el-form-item prop="username" style="flex: 5; margin-bottom: 20px">
				<el-input :validate-event="false" v-model="loginForm.mobile" placeholder="手机号码">
					<template #prefix>
						<el-icon class="el-input__icon"><Iphone /></el-icon>
					</template>
				</el-input>
			</el-form-item>
		</div>

		<el-form-item style="margin-bottom: 30px" prop="password" v-if="loginForm.type == 0">
			<el-input
				:validate-event="false"
				type="password"
				v-model="loginForm.password"
				placeholder="密码"
				show-password
				autocomplete="new-password"
			>
				<template #prefix>
					<el-icon class="el-input__icon"><lock /></el-icon>
				</template>
			</el-input>
		</el-form-item>

		<el-form-item style="margin-bottom: 30px" prop="code" v-if="loginForm.type == 1">
			<el-input style="flex: 2; margin-right: 10px" :validate-event="false" v-model="loginForm.code" placeholder="验证码">
			</el-input>
			<el-button :disabled="timer" @click="verifyCode()" type="primary"
				>{{ timer ? countDown + "秒后重试" : "发送验证码" }}
			</el-button>
		</el-form-item>
	</el-form>
	<div class="forget_password">
		<span @click="toForget()" style="cursor: pointer">忘记密码?</span>
	</div>

	<div class="login-btn">
		<el-button :icon="UserFilled" round @click="login(loginFormRef)" size="large" type="primary" :loading="loading">
			立即登录
		</el-button>
	</div>
	<div class="logon">
		还没有账号？登录即表示您已阅读、理解并同意
		<span @click="show = true" style="color: var(--el-color-primary); cursor: pointer">《速邮达用户服务协议》</span> |
		<span @click="toRegister()" style="color: var(--el-color-primary); cursor: pointer"
			>立即注册<span style="position: relative; top: -2px">👉</span></span
		>
	</div>
	<PrivacyPolicy v-model:show="show"></PrivacyPolicy>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { Login } from "@/api/interface";
import { listMobileAreaCode, sendVerifyCode, getUserInfo } from "@/api/base";
import { ElNotification } from "element-plus";
import { loginApi } from "@/api/modules/login";
import { GlobalStore } from "@/stores";
import { TabsStore } from "@/stores/modules/tabs";
import { KeepAliveStore } from "@/stores/modules/keepAlive";
import { getTimeState } from "@/utils/util";
import { HOME_URL } from "@/config/config";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import { ElMessage } from "element-plus";
import PrivacyPolicy from "@/components/PrivacyPolicy/index.vue";

const emit = defineEmits(["changetitle"]);

const show = ref(false);
const router = useRouter();
const tabsStore = TabsStore();
const keepAlive = KeepAliveStore();
const globalStore = GlobalStore();

// 定义 formRef（校验规则）
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
	// username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
	// password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({ mobile: "", password: "", area_code: 86, type: 1, code: "" });
const login = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(async valid => {
		if (!valid) return;
		loading.value = true;
		try {
			// 1.执行登录接口
			const { data } = await loginApi({ ...loginForm });
			globalStore.setToken(data.gtToken);
			await getInfo();
			// 2.添加动态路由
			await initDynamicRouter();

			// 3.清空 tabs、keepAlive 保留的数据
			tabsStore.closeMultipleTab();
			keepAlive.setKeepAliveName();

			// 4.跳转到首页
			router.push(HOME_URL);
			ElNotification({
				title: getTimeState(),
				message: "欢迎登录 速邮达一般贸易",
				type: "success",
				duration: 3000
			});
		} finally {
			loading.value = false;
		}
	});
};
const getInfo = () => {
	return new Promise<void>((resolve, reject) => {
		getUserInfo({}).then((res: any) => {
			globalStore.setUserInfo(res.data.user);
			resolve(res.data.user);
			// info.value = res.data.user;
		});
	});
};
//区号列表
const codeList: any = ref([]);
async function getcodeList() {
	let res: any = await listMobileAreaCode();
	return res.data.list;
}
onMounted(() => {
	getcodeList().then(res => {
		codeList.value = res;
	});
	// 监听enter事件（调用登录）
	document.onkeydown = (e: any) => {
		e = window.event || e;
		if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
			if (loading.value) return;
			login(loginFormRef.value);
		}
	};
});

const timer = ref<Number | null>(null);
const countDown = ref(120);
const verifyCode = () => {
	if (timer.value !== null) return;
	sendVerifyCode({ area_code: loginForm.area_code, mobile: loginForm.mobile, flag: 2 }).then(() => {
		ElMessage.success("发送短信成功,请注意查收!");
		countDown.value = 119;
		timer.value = window.setInterval(() => {
			countDown.value--;
			if (countDown.value <= 0) {
				if (timer.value) window.clearInterval(timer.value as number);
				countDown.value = 120;
				timer.value = null;
			}
		}, 1000);
	});
};
const toRegister = () => {
	emit("changetitle", "register");
};
const toForget = () => {
	emit("changetitle", "fogetpassword");
};
</script>

<style scoped lang="scss">
@import "../index.scss";
.phoneForm {
	display: flex;
}
</style>
